<?php
session_start();

if (!isset($_SESSION['username'])) {
    header("Location: login.php");
}

$info = isset($_SESSION['info']) ? $_SESSION['info'] : "";
$_SESSION['info'] = "";

$avatar_path = "avatars";

require "db.php";

$q = isset($_GET['q']) ? $_GET['q'] : (isset($_SESSION['q'])? $_SESSION['q']: '');
$_SESSION['q'] = $q;
$count_per_page = isset($_GET['count_per_page']) ? $_GET['count_per_page'] : (isset($_SESSION['count_per_page'])? $_SESSION['count_per_page']:"3");
$_SESSION['count_per_page'] = $count_per_page;
$page = isset($_GET['page']) ? $_GET['page'] : (isset($_SESSION['page'])? $_SESSION['page']:"1");
$_SESSION['page'] = $page;
$contact_count = $db->query("select count(*) from contacts")->fetch()[0];
$pages = ceil($contact_count / $count_per_page);
$offset = ($page - 1) * $count_per_page;

$contacts = $db->query("select * from contacts where name like '%$q%' or phone like '%$q%' limit $offset, $count_per_page");

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>联系人列表</title>
    <link href="https://cdn.bootcss.com/bootswatch/4.3.1/darkly/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/font-awesome.min.css">
</head>

<body>
    <div class="container">
        <?php if($info!="") { ?>
        <p id="info-line" style="position: fixed; top: 0; left: 0; width: 100%; background-color: #2C5F2C; color: white;text-align:center;padding:5px;"><?php echo $info ?></p>
        <?php } ?>
        <h1 class="text-center mt-5 mb-4">联系人列表</h1>
        <nav class="nav justify-content-end">
            <a class="nav-link disabled" href="#" tabIndex="-1">当前用户：<?php echo $_SESSION['name'] ?></a>
            <a class="nav-link" href="#">我的档案</a>
            <a class="nav-link" href="logout.php">退出</a>
        </nav>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item active" aria-current="page">首页</li>
            </ol>
        </nav>

        <div class="row mb-3">
            <div class="col-md-12 col-sm-12">
                <form action="">
                    <input type="text" name="q" placeholder="输入联系人姓名或电话" value="<?php echo $q ?>">
                    <button class="btn btn-primary">搜索</button>
                    每页显示：
                    <select name="count_per_page">
                        <option value="3" <?php if ($count_per_page == 3) {?> selected <?php }?>>3</option>
                        <option value="6" <?php if ($count_per_page == 6) {?> selected <?php }?>>6</option>
                        <option value="12" <?php if ($count_per_page == 12) {?> selected <?php }?>>12</option>
                        <option value="18" <?php if ($count_per_page == 18) {?> selected <?php }?>>18</option>
                        <option value="24" <?php if ($count_per_page == 24) {?> selected <?php }?>>24</option>
                        <option value="30" <?php if ($count_per_page == 30) {?> selected <?php }?>>30</option>
                    </select>
                    条记录
                    <a class="btn btn-primary text-right" href="new-contact.php"><i class="fa fa-plus"></i> 添加联系人</a>
                    <input type="hidden" name="page" value="<?php echo $page ?>">
                </form>
            </div>

        </div>

        <div class="card-deck">

            <?php
if ($contacts !== false) {
    foreach ($contacts as $c) {
        $avatar = $avatar_path . '/person.png';
        // "./avatars/1.jpg"
        if (file_exists("./" . $avatar_path . "/" . $c["id"] . ".jpg")) {
            $avatar = $avatar_path . "/" . $c["id"] . ".jpg";
        }

        ?>
            <div class="col-xl-4 col-md-6 col-sm-12 mb-3">
                <div class="card">
                    <img src="<?php echo $avatar ?>" class="card-img-top" alt="...">
                    <div class="card-body">
                        <h5 class="card-title"><?php echo $c['name'] ?>（编号：<?php echo $c['id'] ?>）</h5>
                        <div class="card-text">
                            <p>性别：<?php echo $c['gender'] == 0 ? '男' : '女' ?></p>
                            <p>出生日期：<?php echo $c['dob'] ?></p>
                            <p>电话：<?php echo $c['phone'] ?></p>
                            <p>电邮：<?php echo $c['email'] ?></p>
                        </div>
                    </div>
                    <div class="card-footer">
                        <small class="text-muted">
                            <a href="edit-contact.php?id=<?php echo $c['id'] ?>"><i class="fa fa-edit fa-2x mr-2"
                                    title="编辑"></i></a>
                            <a href="#" class="delete-contact" data-id="<?php echo $c['id'] ?>"
                                data-url="db-operations.php?operation=delete&id=<?php echo $c['id'] ?>"><i
                                    class="fa fa-trash fa-2x" title="删除"></i></a>

                        </small>
                    </div>
                </div>
            </div>
            <?php
}
}
?>


        </div>
        <nav class="mt-3 mb-5">
            <ul class="pagination">
                <?php if ($page > 1) {?>
                <li class="page-item"><a class="page-link prev" href="#">向前</a></li>
                <?php }?>
                <?php for ($p = 1; $p <= $pages; $p++) {?>
                    <?php if ($page == $p) { ?>
                    <li class="page-item active"><a class="page-link" href="#"><?php echo $p ?></a></li>
                    <?php } else { ?> 
                        <li class="page-item"><a class="page-link" href="#"><?php echo $p ?></a></li>
                    <?php } ?>
                <?php }?>
                <?php if ($page < $pages) {?>
                <li class="page-item"><a class="page-link next" href="#">向后</a></li>
                <?php }?>
            </ul>
        </nav>


    </div>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/popper.js/1.15.0/umd/popper.min.js"></script>
    <script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
    <script>
    $(function(){
        setTimeout(function(){
            p = $("#info-line")
            if(p){
                p.fadeOut();
            }
            console.log("Timeout!")
        },3000)
    });
    $(".delete-contact").on("click", function(e) {
        var id = $(this).attr("data-id");
        var url = $(this).attr("data-url");
        Swal.fire({
            title: "您确认要删除吗？",
            text: "编号为 " + id + " 的联系人将被永久删除!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            cancelButtonText: '不删了',
            confirmButtonText: '是的, 删除吧!'
        }).then((result) => {
        if (result.value) {
            window.location = url;
        }
        })

        // if (confirm("您确认要删除编号为 " + id + " 的联系人吗？")) {
        //     window.location = url;
        // }
    });
    $('select[name="count_per_page"]').on("change", (e) => {
        $('input[name="page"]').val("1");
        $("form").submit();
    })

    $(".pagination").on('click', '.page-link', (e) => {
        e.preventDefault();
        to_page = parseInt(e.target.innerText);
        page = parseInt($("input[name='page']").val());
        if ($(e.target).hasClass('prev'))
            $('input[name="page"]').val(page - 1);
        else if ($(e.target).hasClass('next'))
            $('input[name="page"]').val(page + 1);
        else
            $('input[name="page"]').val(to_page);
        $("form").submit();
    })
    </script>
</body>

</html>